/**
 * 树形视图构建类，专门用于构建TreeView
 * @author 李桥
 */

import jQuery from 'jquery';
window.$ = jQuery;
var self;
export default class TreeView{
    /**
     * @param treeContainer
     * @param treeConfig
     */
    constructor(treeConfig) {
        self = this;
        this.apis = {};
        this._selectedComponents = [];
        this._curOperateComponentInfo = null;
        this.$element = $(treeConfig.treeContainer);
        var defaultCfg = {multiSelect: false, loadingHTML: "<div>Loading...</div>", cacheItems: true};
        //配置项
        this.options = $.extend({},defaultCfg , treeConfig);

        this.$element.on("click", ".tree-item", $.proxy(function (event) {
            this.selectItem(event.currentTarget);
        }, this));
        this.$element.on("click", ".wrap-hover", $.proxy(function (event) {
            this.toggleFolder(event.currentTarget);
        }, this));
        this.$element.on("click", ".selected-all", $.proxy(function (event) {
            this.selectFolder(event.currentTarget);
        }, this));

        this.buildTree();
    }

    /**
     * 初始化构建
     */
    buildTree(){
        //默认配置
        var defaultConfig = {
            "open-icon": "icon-folder-open",
            "close-icon": "icon-folder-close",
            selectable: true,
            "selected-icon": "icon-ok",
            "unselected-icon": "tree-dot"
        };
        defaultConfig = $.extend({}, defaultConfig, this.options);
        this.$element.each(function () {
            var treeContainer = $(this);
            var template =
                '<div class = "tree-folder" style="display:none;">' +
                   '<div class="tree-folder-header">' +
                      '<div class="wrap-hover">' +
                         '<i class="' + defaultConfig["close-icon"] + ' openFolderIcon"></i>' +
                         '<div class="tree-folder-name name-ellipsis_style"></div>' +
                      '</div>' +
                      (self.options.dataSource.config.treeType === "MODELTREE" ? '<span class=\"component-count\"></span>':"")+
                      '<input class="selected-all" type="checkbox"/>' +
                   '</div>	' +
                   '<div class="tree-folder-content"></div>' +
                   '<div class="tree-loader" style="display:none"></div>' +
                '</div>' +
                '<div class="tree-item" style="display:none;">'+
                    (defaultConfig["unselected-icon"] == null ? "" :
                    '<i class="' + defaultConfig["unselected-icon"] + '"></i>') +
                    '<div class="tree-item-name name-ellipsis_style"></div>'+
                '</div>';
            treeContainer.html(template);
            treeContainer.addClass(defaultConfig.selectable == true ? "tree-selectable" : "tree-unselectable");
            self.populate(treeContainer,true);
        });
    }

    // render(){
    //     this.populate(this.$element);
    // }

    populate(element,isOpen){
        var instance = this;
        var treeLoaderElement = element.parent().find(".tree-loader:eq(0)");
        treeLoaderElement.show();
        //data方法定义在IFCTreeRender中，传入配置，和一个回调函数
        this.options.dataSource.data(element.data(),function (datasource) {
            treeLoaderElement.hide();
            $.each(datasource.data,function (key,item) {
                var nodeElement;
                if(item.type === "folder"){
                    //从原有的节点克隆DOM，并填充相应的数据 i-nodeElement j-item
                    nodeElement = instance.$element.find(".tree-folder:eq(0)").clone().show();
                    //加入组件ID
                    nodeElement.attr("id",item.guid);
                    item.selected = false;
                    //保存节点信息到节点的nodeInfo属性中
                    nodeElement.data("nodeInfo",JSON.stringify(item));
                    nodeElement.data("isOpen",false);
                    nodeElement.find(".tree-folder-name").html(item.name);
                    //加入组件数量统计
                    if(self.options.dataSource.config.treeType === "MODELTREE"){
                        nodeElement.find(".component-count").html("(" + item.count +")");
                    }
                    nodeElement.find(".tree-loader").html(instance.options.loadingHTML);
                    var treeFolderHeaderElement = nodeElement.find(".tree-folder-header");
                    treeFolderHeaderElement.data(item);
                    if ("icon-class" in item) {
                        treeFolderHeaderElement.find('[class*="icon-"]').addClass(item["icon-class"])
                    }
                } else {
                    if (item.type === "item"){
                        nodeElement = instance.$element.find(".tree-item:eq(0)").clone().show();
                        nodeElement.find(".tree-item-name").html(item.name);
                        //加入组件ID
                        nodeElement.attr("id",item.guid);
                        item.selected = false;
                        //保存节点信息到节点的nodeInfo属性中
                        nodeElement.data("nodeInfo",JSON.stringify(item));
                      //  nodeElement.data(item);
                        if ("additionalParameters" in item && "item-selected" in item.additionalParameters && item.additionalParameters["item-selected"] == true) {
                            nodeElement.addClass("tree-selected");
                            nodeElement.find("i").removeClass(instance.options["unselected-icon"]).addClass(instance.options["selected-icon"])
                        }
                    }
                }
                if (element.hasClass("tree-folder-header")) {
                    element.parent().find(".tree-folder-content:eq(0)").append(nodeElement)
                } else {
                    element.append(nodeElement)
                }
            });
            if(!isOpen){
                element.parent().find(".tree-folder-content:eq(0)").hide();
            }else{
                element.parent().data("isOpen",true);
            }
            instance.$element.trigger("loaded");
        });
    }

    //选中条目
    selectItem(element){
        if(this.options.selectable == false){
            return;
        }
        // 选中的元素
        var selectedElement = $(element);
        if (selectedElement.hasClass("tree-selected")) {
            selectedElement.removeClass("tree-selected");
            selectedElement.find("i").removeClass(this.options["selected-icon"]).addClass(this.options["unselected-icon"]);
            //从选中的节点信息中删除选中的节点
            for(var i = 0; i < this._selectedComponents.length; i ++) {
                var curObject = this._selectedComponents[i];
                //nodeInfo.selected = false;
                //selectedElement.data("nodeInfo",JSON.stringify(nodeInfo));
                if(selectedElement[0].id === curObject.guid){
                    var nodeInfo = JSON.parse(selectedElement.data("nodeInfo"));
                    nodeInfo.selected = false;
                    selectedElement.data("nodeInfo",JSON.stringify(nodeInfo));
                    this._curOperateComponentInfo = nodeInfo;
                    this._selectedComponents.splice(i,1);
                    this.handleClick("handleItemClick",{curOperateComponentInfo:this._curOperateComponentInfo,selectedComponents:this._selectedComponents});
                    break;
                }
            }

        } else {
            selectedElement.addClass("tree-selected");
            selectedElement.find("i").removeClass(this.options["unselected-icon"]).addClass(this.options["selected-icon"]);
            //将选中的节点放入到选中信息中
            var nodeInfo = JSON.parse(selectedElement.data("nodeInfo"));
            nodeInfo.selected = true;
            selectedElement.data("nodeInfo",JSON.stringify(nodeInfo));
            this._selectedComponents.push(nodeInfo);
            this._curOperateComponentInfo = nodeInfo;
            this.handleClick("handleItemClick",{curOperateComponentInfo:this._curOperateComponentInfo,selectedComponents:this._selectedComponents});
        }
        // var treeSelectedElements = this.$element.find(".tree-selected");
        // var selectedData = [];
        // //如果支持多选
        //  if(this.options.multiSelect){
        //     $.each(treeSelectedElements,function () {
        //
        //     });
        //  }

    }

    /**
     * 打开子项
     * @author 李桥
     * @param element
     */
    toggleFolder(element){
        var element = $(element);
        var parentElement = element.parent();
        var pparentElement = element.parent().parent();
        //获取对应到的组件的ID
        var guid = pparentElement.id;
        if (element.find("." + this.options["close-icon"]).length) {
            if (pparentElement.find(".tree-folder-content").children().length) {
                pparentElement.find(".tree-folder-content:eq(0)").show();
            } else {
                this.populate(parentElement,true)
            }
            pparentElement.find(".icon-plus:eq(0)").removeClass("icon-plus").addClass("icon-minus");
            this.$element.trigger("opened", element.data())
        } else {
            if (this.options.cacheItems) {
                pparentElement.find(".tree-folder-content:eq(0)").hide()
                pparentElement.data("isOpen",false);
            } else {
                pparentElement.find(".tree-folder-content:eq(0)").empty()
            }
            pparentElement.find(".icon-minus:eq(0)").removeClass("icon-minus").addClass("icon-plus");
            this.$element.trigger("closed", element.data())
        }
    }

    /**
     * 选中所有子项
     * @author 李桥
     * @param element
     */
    selectFolder(element){
        var element = $(element);
        var parentElement = element.parent();
        var pparentElement = element.parent().parent();
        //获取对应到的组件的ID
        var guid = parentElement.id;
        //检查子节点是否已经渲染，如果没有渲染，则先执行渲染
        if(!pparentElement.find(".tree-folder-content").children().length){
            var isOpen = pparentElement.data("isOpen");
            this.populate(parentElement,isOpen);
        }
        //
        if(parentElement.hasClass("tree-folder-header")&& parentElement.find(".selected-all")[0].checked){
            var children = pparentElement.find(".tree-folder-content:eq(0)").children();
            var selectedKeys = this._selectedComponents.map(function (item,index,array) {
                return item.guid;
            });
            this._recursionHandle(children,selectedKeys,[],true);
            this.handleClick("handleFolderClick",{deSelectedComponents:[],selectedComponents:this._selectedComponents});
        }
        else{
            var children = pparentElement.find(".tree-folder-content:eq(0)").children();
            var selectedKeys = this._selectedComponents.map(function (item,index,array) {
                return item.guid;
            });

            var deSelectedComponents = [];
            this._recursionHandle(children,selectedKeys,deSelectedComponents,false);

            //消除删除项
            for(var i = 0; i < this._selectedComponents.length; i ++){
                var curComponent = this._selectedComponents[i];
                if(!curComponent){
                    this._selectedComponents.splice(i,1);
                    i--;
                }
            }
            this.handleClick("handleFolderClick",{deSelectedComponents:deSelectedComponents,selectedComponents:this._selectedComponents});
        }
    }
    //选择多条数据
    selectedItems () {
        var treeSelectedElements = this.$element.find(".tree-selected");
        var selectedItems = [];
        $.each(treeSelectedElements, function (key, item) {
            selectedItems.push($(item).data());
            console.log($(item).data());
        });
        return selectedItems;
    }

    handleClick(api,data){
        var handler = self.apis[api];
        if(handler){
            handler(data);
        }else{
            console.warn("你还没有注册相关API,如若要使用相关响应功能，需要注册API，方式如：TreeViewApi.registerApi('handClick',handler)");
        }
    }

    /**
     * 递归处理节点（包含子项）
     * @param node
     * @param selectedKeys
     * @private
     */
    _recursionHandle(childNodes,selectedKeys,deSelectedComponents,checked){
        //选中checkbox
        if(checked){
            for(var i = 0; i < childNodes.length; i ++){
                var curNode = $(childNodes[i]);
                //如果是不包含子项
                if (!curNode.hasClass("tree-folder")){
                    var nodeInfo = JSON.parse(curNode.data("nodeInfo"));
                    if(selectedKeys.indexOf(nodeInfo.guid)<0){
                        curNode.toggleClass("tree-selected");
                        var icon =  $(curNode.find("i")[0]);
                        if(!icon.hasClass("icon-ok")){
                            icon.removeClass("icon-remove");
                            icon.addClass("icon-ok");
                        }
                        nodeInfo.selected = !nodeInfo.selected;
                        curNode.data("nodeInfo",JSON.stringify(nodeInfo));
                        this._selectedComponents.push(nodeInfo);
                    }
                }
                //包含子项(递归)
                else{
                    var nodeChildren = curNode.find(".tree-folder-content:eq(0)").children();
                    //优先吧子项渲染出来，之 后在递归处理，否则会出现问题
                    if(!nodeChildren.length){
                        var isOpen = curNode.data("isOpen");
                        this.populate(curNode.find(".tree-folder-header:eq(0)"),isOpen);
                    }
                    nodeChildren = curNode.find(".tree-folder-content:eq(0)").children();
                    //修该checkbox样式
                    curNode.find(".selected-all")[0].checked = true;
                    this._recursionHandle(nodeChildren,selectedKeys,deSelectedComponents,checked);
                }
            }
        }
        else{
            for(var i = 0; i < childNodes.length; i ++){
                var curNode = $(childNodes[i]);
                if (!curNode.hasClass("tree-folder")){
                    var nodeInfo = JSON.parse(curNode.data("nodeInfo"));
                    var existIndex = selectedKeys.indexOf(nodeInfo.guid);
                    if(existIndex >= 0){
                        curNode.toggleClass("tree-selected");
                        var icon =  $(curNode.find("i")[0]);
                        icon.addClass("icon-remove");
                        icon.removeClass("icon-ok");
                        nodeInfo.selected = !nodeInfo.selected;
                        curNode.data("nodeInfo",JSON.stringify(nodeInfo));
                        deSelectedComponents.push(nodeInfo);
                        //标记删除项
                        this._selectedComponents[existIndex] = null;
                    }
                }
                else{
                    var nodeChildren = curNode.find(".tree-folder-content:eq(0)").children();
                    //修该checkbox样式
                    curNode.find(".selected-all")[0].checked = false;
                    this._recursionHandle(nodeChildren,selectedKeys,deSelectedComponents,checked);
                }
            }
        }
    }

    /**
     * 注册点击响应API
     * @author 李桥
     * @param api
     * @param handler
     */
    registorApi(api,handler){
        if(self.apis[api]){
            return ;
        }else{
            self.apis[api] = handler
        }
    }
}